﻿using AduSkin.Controls.Metro;
using HsServerHa.Entity.Models;
using HsServerHa.Utility;
using HsServerHa.Utility.DataHelper;
using HsServerHa.Utility.FileHelper;
using HsServerHa.Utility.NetWork;
using HsServerHa.Utility.SQLite;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Net.Sockets;
using System.Windows.Forms;

namespace HsServerHa.Common
{
    public static class MasterSlaveSwitchHelper
    {
        /// <summary>
        /// 切换主机
        /// </summary>
        public static async void SwitchMaster()
        {           
            var list = await SQLiteHelper.TableAsync<VirtuallyManageEntity>().ToListAsync().ConfigureAwait(false);
            if (list.Count > 0)
            {
                var msFirst = list.FirstOrDefault();                       
                NetWorkHelper.DeleteVirtualIP(msFirst?.VirtuallyIP);            
                int NTEContext = 0;
                int NTEInstance;
                string virtualIP = msFirst.VirtuallyIP; // 虚拟IP地址
                string subnetMask = msFirst.SubnetMask; // 子网掩码
                int interfaceIndex = NetWorkHelper.GetInterfaceIndex(msFirst.NetworkCardName); // 网卡接口索引

                if (interfaceIndex == -1)
                {
                    LoggerHelper.Error("网卡配置错误！");
                    return;
                }

                var result = NetWorkHelper.AddVirtualIPAddress((uint)BitConverter.ToInt32(System.Net.IPAddress.Parse(virtualIP).GetAddressBytes(), 0), (uint)BitConverter.ToInt32(System.Net.IPAddress.Parse(subnetMask).GetAddressBytes(), 0), interfaceIndex, out NTEContext, out NTEInstance);
                if (result != 0)
                {                  
                    LoggerHelper.Error("切换网卡失败！");                  
                    return;
                }             
                //修改虚拟表的虚拟KEy             
                App.IsEntrustMaster = true;
                App.XtDisconnectNum = -10;

                //修改绑定数据              
                var bindList = await SQLiteHelper.TableAsync<MasterSlaveBindEntity>().ToListAsync().ConfigureAwait(false);

                if (bindList.Count > 0)
                {                  
                    var bindFirst = bindList?.FirstOrDefault();
                    if (bindFirst != null)
                    {                       
                        IniFileConfig.Current.SetStringValue("UserConfig", "IsMainPC", "true");
                        if (bindFirst.SlaveIP == App.CurrIP)
                        {
                            SQLiteHelper.ExecuteSql($"update MasterSlaveBind set MasterIP='{bindFirst.SlaveIP}',SlaveIP='{bindFirst.MasterIP}',IsMaster='true' ");
                        }
                        else
                        {
                            SQLiteHelper.ExecuteSql($"update MasterSlaveBind set IsMaster='true' ");
                        }
                        App.isMaster = true;
                        App.MasterIP = msFirst.CurrIP;
                      
                        var listXt = await SQLiteHelper.TableAsync<HeartEntity>().Where(x => x.IsLocal == "true").ToListAsync().ConfigureAwait(false);

                        App.XtIP = listXt[0].HeartIP;                      
                        App.VirtuallyIP = msFirst.VirtuallyIP;
                        App.GatewayIP = msFirst.Gateway;
                                              
                        //保存系统配置信息
                        SaveSystemInfo();
                        LoggerHelper.SetInfo("切换主机保存系统配置信息成功", "系统监测");
                        try
                        {                        
                            if (App.proxSocket == null)
                            {
                                return;
                            }
                            App.proxSocket.Shutdown(SocketShutdown.Both);
                            //Shutdown掉Socket后主线程停止10ms，保证Socket的Shutdown完成
                            System.Threading.Thread.Sleep(10);
                            //关闭客户端Socket,清理资源
                            App.proxSocket.Close();

                            App.proxSocket = null;
                            App.socketServer = null;
                        }
                        catch (Exception ex)
                        {
                            LoggerHelper.SetInfo($"心跳正常，参考IP正常，虚拟IP异常，主机IP异常，异常报错{ex.Message}", "系统监测");
                            App.proxSocket = null;
                            App.socketServer = null;
                        }

                    }

                }
               
            }
        }
        /// <summary>
        /// 保存系统配置信息到配置文件
        /// </summary>
        public static void SaveSystemInfo()
        {
            //修改系统配置信息           
            var systemInfo = new SystemInfo();
            systemInfo.SwitchHostTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            systemInfo.SwitchHostTimeStamp = DateTimeOffset.Now.ToUnixTimeSeconds();
            SystemConfigHelper.WriteSystemConfig(JsonConvert.SerializeObject(systemInfo));
        }

        /// <summary>
        /// 切换从机
        /// </summary>
        public async static void SwitchSlave()
        {          
            var listBind = await SQLiteHelper.TableAsync<MasterSlaveBindEntity>().ToListAsync().ConfigureAwait(false);          
            var list = await SQLiteHelper.TableAsync<VirtuallyManageEntity>().ToListAsync().ConfigureAwait(false);
            var bindFirst = listBind?.FirstOrDefault();

            //将主切换成从
            App.isMaster = false;
            App.MasterIP = bindFirst.SlaveIP;
            App.VirtuallyIP = bindFirst.VirtuallyIP;      
            var heartList = await SQLiteHelper.TableAsync<HeartEntity>().ToListAsync().ConfigureAwait(false);
            var msFirst = list?.FirstOrDefault();
            if (msFirst != null)
            {                
                NetWorkHelper.DeleteVirtualIP(msFirst?.VirtuallyIP);             
                IniFileConfig.Current.SetStringValue("UserConfig", "IsMainPC", "false");

                if (App.CurrIP == bindFirst.MasterIP)
                {
                    SQLiteHelper.ExecuteSql($"update MasterSlaveBind set MasterIP='{bindFirst.SlaveIP}',SlaveIP='{bindFirst.MasterIP}',IsMaster='false' ");
                }
                else
                {
                    SQLiteHelper.ExecuteSql($"update MasterSlaveBind set IsMaster='false' ");
                }
                App.XtIP = heartList[0].MasterHeartIPBind;              
                try
                {
                    App.proxSocket.Shutdown(SocketShutdown.Both);
                    //Shutdown掉Socket后主线程停止10ms，保证Socket的Shutdown完成
                    System.Threading.Thread.Sleep(10);
                    //关闭客户端Socket,清理资源
                    App.proxSocket.Close();

                    App.proxSocket = null;
                    App.socketServer = null;
                }
                catch (Exception)
                {
                }
             
            }
        }
    }
}
